#include "Map.h"


Map::Map(char* map)
{

	//Loading the XML file.
	TiXmlDocument doc(map);

	if (!doc.LoadFile())
	{
		std::cout << "Failed to load map: " << std::endl;
	}
	else
	{

		std::cout << std::endl << "Loading Map: " << map << std::endl;

	//Getting the root element of the XML file.
	TiXmlElement* rootElem = doc.RootElement();

	//Getting some info about the map and tiles.
	mapSizeX = atoi(rootElem->Attribute("width"));
	mapSizeY = atoi(rootElem->Attribute("height"));
	tileSizeX = atoi(rootElem->Attribute("tilewidth"));
	tileSizeY = atoi(rootElem->Attribute("tileheight"));

	//Getting to the image element.
	TiXmlElement* Elem = rootElem->FirstChildElement("tileset");
	Elem = Elem->FirstChildElement("image");

	//Getting tileset size.
	tilesetSizeX = atoi(Elem->Attribute("width"));
	tilesetSizeY = atoi(Elem->Attribute("height"));
	
	tilesPerLine = tilesetSizeX/tileSizeX;

	//Loading the texture.
	std::string textureFile = Elem->Attribute("source");
	tileset.loadFromFile("Assets/" + textureFile);

	Elem = rootElem->FirstChildElement("layer");
	Elem = Elem->FirstChildElement("data");
	
	//Getting first tile element
	TiXmlElement* tileElem = Elem->FirstChildElement();

	for(int y = 0; y < mapSizeY; y++)
	{
		for (int x = 0; x < mapSizeX; x++)
		{
			sf::Sprite sprite;
			int currentTile = atoi(tileElem->Attribute("gid"));
			
			//If there is a tile.
			if (currentTile > 0){

			currentTile--;

			int texY = floor(currentTile/tilesPerLine)*32;
			int texX = (currentTile%(tilesetSizeX/tileSizeX))*32;

			sprite.setTexture(tileset);
			sprite.setPosition(x*tileSizeX, y*tileSizeY);
			sprite.setTextureRect(sf::IntRect(texX, texY, tileSizeX, tileSizeY));

			tiles.push_back(sprite);
			}

			//Going to the next tile element.
			tileElem = tileElem->NextSiblingElement();
		}
	}

}

}

void Map::draw(sf::RenderWindow& window)
{
	for (int x = 0; x < tiles.size(); x++)
	{
		window.draw(tiles[x]);
	}
}